import React, { useEffect, useState } from 'react'
import { Button, Dropdown, message, notification, Spin } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import { getSupplierList, updateSupplierStatusBatch, exportSupplierListExcel, supplierInfoPush } from '@/api/supplier'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { OperationLogType, PUSH_STATE_STATUS_OPTIONS, STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import './index.less'
import { useNavigate } from 'react-router-dom'
import { CooperateStatusOptions, SUPPLIER_RATING_OPTIONS } from '@/constant/supplier'
import { useAppSelector } from '@/store/hooks'
import { getProductClassConfigByType } from '@/api/goods'
import { UploadOutlined, PlusOutlined, DownOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
import useViewLogs from '@/hooks/useViewLogs'
import LogsDrawer from '@/components/LogsDrawer'
import PermissionButton from '@/components/PermissionButton'
import useCachePage from '@/hooks/useCachePage'
import useGetArea from '@/hooks/useGetArea'
import { PURCHASEWAY_OPTIONS } from '@/constant/purchase'
import { exportNotification } from '@/utils/util'
const Index: React.FC = () => {
  const [form] = useForm()
  const navigate = useNavigate()
  const [classIdOptions, setclassIdOptions] = useState<IOptionItem[]>([])
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const [selectInfo, setselectInfo] = useState<ITableData[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const [areaList, setareaList] = useState<number[]>([])
  const [spinning, setspinning] = useState<boolean>(false)
  const { AreaOptions, loadAreaData } = useGetArea(areaList)
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'supplierId',
    OperationLogType.SUPPLIER,
  )
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getSupplierList, {
    form: form,
    defaultFieldsParams: {
      useStatus: 1,
      cooperateStatus: 1,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [exportLoading, setexportLoading] = useState(false)
  const { setCachePage, getCachePage } = useCachePage()
  useEffect(() => {
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('onSupplier')) {
      items.push({
        key: STATUSNUM.OPEN + '',
        label: '批量启用',
      })
    }
    if (buttonCodeList.includes('offSupplier')) {
      items.push({
        key: STATUSNUM.CLOSE + '',
        label: '批量停用',
      })
    }
    if (buttonCodeList.includes('pushSupplier')) {
      items.push({
        key: 'PUSH',
        label: '触发CB推送',
      })
    }
    setmenuItems(items)
    getProductClassConfig()
  }, [])
  useEffect(() => {
    if (AreaOptions.length > 0 && AreaOptions?.every((item) => item.children === undefined)) {
      const cacheData = getCachePage()
      if (cacheData == null) {
        search({ ...params, useStatus: 1, cooperateStatus: 1 })
        setCachePage({ ...params, useStatus: 1, cooperateStatus: 1 })
      } else {
        setareaList(cacheData.area)
        const nullNum = cacheData?.area?.filter((item: number | null) => item === null)?.length
        form.setFieldsValue({
          ...cacheData,
          area: nullNum === 0 || nullNum === 1 ? cacheData.area : nullNum === 2 ? [cacheData.area[0]] : null,
          cooperateStatus: cacheData.cooperateStatus != null ? cacheData.cooperateStatus : null,
          useStatus: cacheData.useStatus != null ? cacheData.useStatus : null,
        })
        delete cacheData.AreaOptions
        delete cacheData.area
        search({
          ...cacheData,
          cooperateStatus: cacheData.cooperateStatus != null ? cacheData.cooperateStatus : null,
          useStatus: cacheData.useStatus != null ? cacheData.useStatus : null,
        })
      }
    }
  }, [AreaOptions])
  const onStatus = async (info: ITableData) => {
    const res = await updateSupplierStatusBatch({
      status: info.useStatus == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE,
      id: info.supplierId,
    })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId + '',
        }
      }) || []
    setclassIdOptions(classIdOptions)
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectKeys(keys)
    setselectInfo(info)
  }
  const handleChangeStatus = async (userStatus: 0 | 1) => {
    if (selectKeys.length === 0) {
      message.warning('请勾选需要改变状态的列表数据！')
      return
    }
    const res = await updateSupplierStatusBatch({ userStatus, supplierIds: selectKeys })
    if (res.code === 200) {
      message.success('操作成功')
      setselectKeys([])
      setselectInfo([])
      search(params)
    }
  }
  const handleClickMore = async (info: any) => {
    console.log(info)
    if (info.key == STATUSNUM.OPEN) {
      handleChangeStatus(1)
    }
    if (info.key == STATUSNUM.CLOSE) {
      handleChangeStatus(0)
    }
    if (info.key == 'PUSH') {
      if (selectKeys.length === 0) {
        message.warning('请勾选需要改变状态的列表数据！')
        return
      }
      const res = await supplierInfoPush({
        supplierCodes: selectInfo.map((item) => item.supplierCode),
      })
      if (res.code === 200) {
        message.success('触发推送成功，请稍后查看！')
        setselectKeys([])
        setselectInfo([])
        search(params)
      }
    }
  }
  return (
    <PageContainer className="suppliermgr_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) =>
          onValuesChange(changedValues, ['keyword', 'supplierShortName', 'contactName'], form)
        }
        searchConfig={[
          {
            label: '供应商',
            name: 'keyword',
            type: 'Input',
            placeholder: '供应商名称/供应商编码',
          },
          {
            label: '简称',
            name: 'supplierShortName',
            type: 'Input',
          },
          {
            label: '供应商分类',
            name: 'supplierClassificationCodes',
            type: 'Select',
            option: DICTDATA.supplier_type,
            config: {
              mode: 'multiple',
              optionFilterProp: 'label',
              maxTagCount: 'responsive',
            },
          },
          {
            label: '可供应大类',
            name: 'mainClassIdList',
            type: 'Select',
            option: classIdOptions,
            config: {
              mode: 'multiple',
              optionFilterProp: 'label',
              maxTagCount: 'responsive',
            },
          },
          {
            name: 'purchaseTypes',
            label: '采购模式',
            type: 'Select',
            option: PURCHASEWAY_OPTIONS,
            config: {
              mode: 'multiple',
              optionFilterProp: 'label',
              maxTagCount: 'responsive',
            },
          },
          {
            label: '区域',
            name: 'locationCode',
            type: 'Select',
            option: DICTDATA.sp_area,
          },
          {
            name: 'area',
            label: '省市区：',
            type: 'Cascader',
            option: AreaOptions,
            placeholder: '请选择省市区',
            config: { loadData: loadAreaData, changeOnSelect: true },
          },
          {
            label: '联系人',
            name: 'contactName',
            type: 'Input',
          },
          {
            label: '供应商评级',
            name: 'levelCode',
            type: 'Select',
            option: SUPPLIER_RATING_OPTIONS,
          },
          {
            label: '合作状态',
            name: 'cooperateStatus',
            type: 'Select',
            option: CooperateStatusOptions,
          },
          {
            label: '供应商状态',
            name: 'useStatus',
            type: 'Select',
            option: STATUSBANDOPTIONS,
          },
          {
            label: '推送状态',
            name: 'pushStatus',
            type: 'Select',
            option: PUSH_STATE_STATUS_OPTIONS,
          },
        ]}
        onFinish={(vals: any) => {
          setselectKeys([])
          setselectInfo([])
          const { area, ...setvals } = vals
          const provinceId = area?.[0] || null
          const cityId = area?.[1] || null
          const areaId = area?.[2] || null
          const paramsData = {
            ...setvals,
            provinceId,
            cityId,
            areaId,
          }
          search(paramsData)
          setCachePage({
            ...paramsData,
            area: [provinceId, cityId, areaId],
            AreaOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectKeys([])
          setselectInfo([])
          setCachePage({ current: 1, size: 10, useStatus: 1, cooperateStatus: 1 })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                type="primary"
                permission="addSupplier"
                onClick={() => {
                  navigate('/supplier/create/add')
                }}
                icon={<PlusOutlined />}
              >
                新建供应商
              </PermissionButton>
              {menuItems.length > 0 ? (
                <Dropdown
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              ) : null}
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportSupplier"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectKeys.length > 0) {
                    paramsData.supplierIds = selectKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await exportSupplierListExcel(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectKeys([])
                      setselectInfo([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        columns={useIndexColumns(navigate, onStatus, viewLogs)}
        {...tableProps}
        rowKey={(row) => row.supplierId}
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
        isScrollY
      />
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
